package com.eva.statDemo;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.eva.statDemo.stat.Debuger;

/**
 * Created by Administrator on 2015/9/15.
 */
public abstract class BaseActivity extends Activity implements View.OnClickListener {


    protected Messenger messenger;
    protected Messenger sendMessenger;

    protected Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            send();
        }
    };

    protected ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder binder) {
            messenger = new Messenger(binder);
            Debuger.LOGD("onServiceConnected ");
            send();
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            Debuger.LOGD("onServiceDisconnected");
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView title = (TextView) findViewById(R.id.title);
        title.setText(getName());
        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(this);
    }

    protected void bind() {
        Intent intent = new Intent();
        intent.setClass(this, MessageService.class);
        bindService(intent, conn, Context.BIND_AUTO_CREATE);
    }

    protected void send() {
        sendMessenger = new Messenger(handler);
        Message msg = Message.obtain(null, 0);
        msg.replyTo = sendMessenger;
        try {
            messenger.send(msg);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    protected abstract String getName();

}
